﻿/*
 * 地信中心附件接口专用
 * */
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ChBusiness;

using ChBusiness.Common;
using ChBusiness.User;
using ChBusiness.Wsbs;
using Common;
using ChBusiness.Struct;

public partial class Common_AttachmentFileUpload : System.Web.UI.Page
{
    private ShenBaoSubmit submit = new ShenBaoSubmit();
    private UploadFileClass ufcGloab = new UploadFileClass();

    //设置文件上传属性
    string strKeyId = "id";
    string strFileStoreFieldName = "FILEDATA";
    string strFileTypeFieldName = "FILETYPE";
    string strTableName = "xt_serial_attachment";

    string strStoreKeyFieldName = "AppDataId";
    string strStoreResourceFieldName = "FILENAME";
    string strStoreResourceType = "insert";
    string strStoreResourceNameControlName = "id";
    string strStoreControlValue = "";

    /// <summary>
    /// 产生的新ID值
    /// </summary>
    public string NewIdValue
    {
        get
        {
            if (!string.IsNullOrEmpty(ViewState["NewId"].ToString()))
            {
                return ViewState["NewId"].ToString();
            }
            else
            {
                return string.Empty;
            }
        }
    }
    public event EventHandler<EventArgs> _afterUploadedEvent;
    /// <summary>
    /// 捕获ONCHANGE事件
    /// </summary>
    public event EventHandler<EventArgs> AfterUploadedEvent
    {
        add
        {
            _afterUploadedEvent += value;
        }
        remove
        {
            _afterUploadedEvent -= value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {        
        if (!IsPostBack)
        {
            if (Request["flowname"] != null)
                ViewState["type"] = Request["flowname"];
            else
                ViewState["type"] = SystemConfig.InterfaceSerialName;
            if (Request["NewsId"] != null)
            {
                try
                {
                    //ViewState["NewsId"] = Request["NewsId"];
                    //添加DES解密 addby zhongjian 20091211
                    //string strTestCode = Common.Encode.DesEncrypt("5732", "gjchdxzx");
                    string strKey = System.Configuration.ConfigurationManager.AppSettings["DXInterfaceKey"];
                    ViewState["NewsId"] = Common.Encode.DesDecrypt(Request["NewsId"], strKey);
                }
                catch
                {
                    Response.Write("输入NewsId参数无效！");
                    Response.End();
                }
                BindData();

                //判断是否显示上传按钮
                bool bIsRead = submit.IsShouLi(ViewState["NewsId"].ToString());

                if (bIsRead)
                {
                    btnUpFile.Enabled = false;
                }
            }
            else
            {
                Response.Write("请输入NewsId参数！");
                Response.End();
            }
           
        }

        DeleteResource();
    }    

    /// <summary>
    /// 删除附件
    /// </summary>
    private void DeleteResource()
    {
        if (!string.IsNullOrEmpty(Request["id"]) && !string.IsNullOrEmpty(Request["flowname"]) && !string.IsNullOrEmpty(Request["NewsId"]) && Request["action"].CompareTo("delete") == 0)
        {
            ufcGloab.DeleteStoreFile("xt_serial_attachment", "id", Request["id"]);

            BindData();
        }
    }

    /// <summary>
    /// 绑定数据源,绑定datagrid
    /// </summary>
    private void BindData()
    {
        DataTable dtSource = ufcGloab.GetAttinterfaceInfo(ViewState["type"].ToString(), ViewState["NewsId"].ToString());
        CustomGridView1.DataSource = dtSource;

        int nPage = Convert.ToInt32(ConfigurationManager.AppSettings["pagesize"].ToString());
        CustomGridView1.PageSize = nPage;
        CustomGridView1.RecordCount = dtSource.Rows.Count;
        CustomGridView1.DataBind();
       
    }
    /// <summary>
    /// 绑定数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void CustomGridView1_OnLoadData(object sender, EventArgs e)
    {
        BindData();
    }
    /// <summary>
    /// 行创建
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void CustomGridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink hlTemp = e.Row.FindControl("hlDelete") as HyperLink;
            bool bIsRead = submit.IsShouLi(ViewState["NewsId"].ToString());

            if (!bIsRead)
            {
                DataRowView dtr = (DataRowView)e.Row.DataItem;

                if (hlTemp != null)
                {
                    if (dtr != null)
                    {
                        string strKey = ConfigurationManager.AppSettings["DXInterfaceKey"];
                        string strnewsid = Common.Encode.DesEncrypt(ViewState["NewsId"].ToString(), strKey);
                        hlTemp.Attributes.Add("OnClick", "return confirm('确定要删除该附件?')");
                        hlTemp.NavigateUrl = string.Format("AttachmentFileUpload.aspx?id={0}&NewsId={1}&flowname={2}&action=delete",
                            dtr["attachid"], strnewsid, ViewState["type"].ToString());
                    }
                }
            }
            else
            {
                hlTemp.Enabled = false;
            }
        }
    }
    /// <summary>
    /// 上传控件是否显示
    /// </summary>
    /// <param name="row">当前行</param>
    /// <returns>true:显示,false:隐藏</returns>
    /// <!--addby zhongjian 20090828-->
    public bool GetFileAtt(IDataItemContainer row)
    {
        string strName = DataBinder.Eval(row.DataItem, "attachid").ToString();
        if (strName == null || strName == "")
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    /// <summary>
    /// 当附件模板为空时不显示查询结果(隐藏.点的显示)
    /// </summary>
    /// <param name="row">当前行</param>
    /// <returns>返回要显示的信息</returns>
    /// <!--addby zhongjian 20090831-->
    public string GetFileName(IDataItemContainer row)
    {
        string strName = DataBinder.Eval(row.DataItem, "mudulefilename").ToString();
        if (strName == null || strName == "" || strName == ".")
        {
            return "";
        }
        else
        {
            return strName;
        }
    }
    /// <summary>
    /// 当附件上传材料名称为空时不显示查询结果(隐藏.点的显示)
    /// </summary>
    /// <param name="row">当前行</param>
    /// <returns>返回要显示的信息</returns>
    /// <!--addby zhongjian 20090831-->
    public string GetAttName(IDataItemContainer row)
    {
        string strName = DataBinder.Eval(row.DataItem, "attachfilename").ToString();
        if (strName == null || strName == "" || strName == ".")
        {
            return "";
        }
        else
        {
            return strName;
        }
    }
    protected string GetCailiao(IDataItemContainer row)
    {
        string strName = DataBinder.Eval(row.DataItem, "ATTACHFILENAME").ToString();

        if (strName == null || strName == "")
        {
            return "";
        }
        else
        {
            return "none";
        }
    }
    protected string GetFile(IDataItemContainer row)
    {
        string strName = DataBinder.Eval(row.DataItem, "ATTACHFILENAME").ToString();

        if (strName == null || strName == "")
        {
            return "none";
        }
        else
        {
            return "";
        }
    }

    protected string GetUpload(IDataItemContainer row)
    {
        string strName = DataBinder.Eval(row.DataItem, "ATTACHFILENAME").ToString();

        if (strName == null || strName == "")
        {
            return "";
        }
        else
        {
            return "none";
        }
    }
    protected void btnUpFile_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < CustomGridView1.Rows.Count; ++i)
        {
            bool bPromise = false;
            if (!string.IsNullOrEmpty(strStoreResourceType))
            {
                if (strStoreResourceType.ToLower().CompareTo("insert") == 0)
                {
                    bPromise = true;
                }
            }

            GridViewRow row = CustomGridView1.Rows[i];
            FileUpload file1 = (FileUpload)row.FindControl("file1");
            strStoreControlValue = file1.ToolTip;
            //验证文件类型
            String strFileExtension = System.IO.Path.GetExtension(file1.FileName);
            if (strFileExtension != null && strFileExtension != "")
            {
                string strFileName = file1.FileName.Replace(strFileExtension, "");
                strFileExtension = strFileExtension.Replace(".", "").ToLower();
                bool bOk = ufcGloab.HaveValideFileExtension(strFileExtension);
                if (bOk)
                {
                    FileUploadStruct _fileUploadStruct = new FileUploadStruct();
                    _fileUploadStruct.KeyId = strKeyId;
                    _fileUploadStruct.KeyIdValue = strStoreControlValue;
                    _fileUploadStruct.TableName = strTableName;
                    _fileUploadStruct.FileStoreFieldName = strFileStoreFieldName;
                    _fileUploadStruct.FileTypeFieldName = strFileTypeFieldName;
                    _fileUploadStruct.SyncType = "2";

                    //开始上传                
                    _fileUploadStruct.FileTypeFieldValue = strFileExtension;
                    _fileUploadStruct.FileBytes = file1.FileBytes;

                    DataStoreType storeType = DataStoreType.Update;

                    if (bPromise)
                    {
                        storeType = DataStoreType.Insert;
                        _fileUploadStruct.StoreKeyFieldName = strStoreKeyFieldName;
                        _fileUploadStruct.StoreKeyValue = ViewState["NewsId"].ToString();
                        _fileUploadStruct.StoreResourceFieldName = strStoreResourceFieldName;
                        _fileUploadStruct.StoreResourceNameValue = strFileName;

                        Control ctrlTemp = Page.FindControl(strStoreResourceNameControlName);
                        if (ctrlTemp != null)
                        {
                            TextBox txtCtrl = ctrlTemp as TextBox;
                            if (txtCtrl.Text == "")
                            {
                                _fileUploadStruct.StoreResourceNameValue = strFileName;
                            }
                            else
                            {
                                _fileUploadStruct.StoreResourceNameValue = txtCtrl.Text;
                            }
                        }
                    }

                    int nResult = ufcGloab.StoreCailiaoUploadFile(_fileUploadStruct, storeType, strStoreControlValue);

                    if (nResult == 1)
                    {
                        BindData();
                        WindowAppear.WriteAlert(this.Page, "文件上传成功！");

                        ViewState["NewId"] = ufcGloab.NewId;

                        //上传成功后触发事件
                        if (_afterUploadedEvent != null)
                        {
                            _afterUploadedEvent(sender, e);
                        }
                    }
                }
                else
                {
                    WindowAppear.WriteAlert(this.Page, "对不起，系统不支持您选择上传的文件类型！");
                }
            }
        }
    }
}
